import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Table, Button, Row, Col, Layout, Pagination, Breadcrumb, Menu, Dropdown, Popconfirm, Spin, Icon, Input, Card, Modal, message } from 'antd';
import style from '../../styles/TableCss.less';
import { Link } from 'dva/router';
// import reqwest from 'reqwest';
import InStyle from '../../styles/Info.less';
import SalerDirector from './SalerDirector.js';
import EditableCell from '../../components/EditableCell.js';
import { reqwest_post } from '../../utils/Reqwest.js';
const {  Content, Footer } = Layout;
const Search = Input.Search;

import ReactExport from "react-data-export";

const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;

// const { RangePicker } = DatePicker;

class Orders extends React.Component {
	constructor(props) {
		super(props);
		this.state= {
      q: '',
			data: [],
      list: [],
      role: JSON.parse(window.localStorage['setting']).role,
			dropDown: ' 所有销售订单',
      tab: "1",
			columns: [
        {
          title: '订单号',
          dataIndex: 'orders',
        }, {
          title: '客户名称',
          dataIndex: 'name',
          width: '20%'
        }, {
          title: '手机',
          dataIndex: 'mobile'
        }, {
          title: '面积',
          dataIndex: 'size'
        }, {
          title: '订单状态',
          dataIndex: 'status',
        }, {
          title: '预估产品价格',
          dataIndex: 'money',
          width: '100px',
          render: (text, record, index) => this.renderColumns(this.props.orders.table, index, 'money', text.value),
        }, {
          title: '操作',
          key: 'action',
          render: (text, record, index) => {
          const { editable } = this.props.orders.table[index].money;
            return (
              <div className="editable-row-operations">
                {
                  editable ?
                    <span>
                      <a onClick={() => this.editDone(index, 'save',record)}>保存</a>
                      <span className="ant-divider" />
                      <Popconfirm title="放弃此次操作?" onConfirm={() => this.editDone(index, 'cancel',record)}>
                        <a>返回</a>
                      </Popconfirm>
                    </span>
                    :
                    <span>
                      <a onClick={() => this.edit(index,record)}>编辑</a>
                      <span className="ant-divider" />
                      <Link onClick={() => { window.sessionStorage['details'] = JSON.stringify(text)}}  to={{pathname:'/app/deaor',query:{current:this.props.location.query.current,wudi:JSON.stringify(text),ma:'/app/newor'}}}>详情</Link>

                    </span>
                }
              </div>
            )
          }
        }
      ],
      _columns:[{
        title:'订单号',
        dataIndex:'orders'
      },{
        title:'客户名称',
        dataIndex:'name',
        width:'20%'
      },{
        title:'手机',
        dataIndex:'mobile'
      },{
        title:'面积',
        dataIndex:'size'
      },{
        title:'订单状态',
        dataIndex:'status',
      },{
        title:'预估产品价格',
        dataIndex:'money',
        render: (text, record, index) => this.renderColumns(this.props.orders.table, index, 'money', text.value),
      },{
        title:'订单所有者',
        dataIndex:'owner_name',
      },{
        title:'操作',
        key:'action',
        render:(text, record, index) => {
        const { editable } = this.props.orders.table[index].money;
          return (
            <div className="editable-row-operations">
              {
                editable ?
                  <span>
                    <a onClick={() => this.editDone(index, 'save',record)}>保存</a>
                    <span className="ant-divider" />
                    <Popconfirm title="放弃此次操作?" onConfirm={() => this.editDone(index, 'cancel',record)}>
                      <a>返回</a>
                    </Popconfirm>
                  </span>
                  :
                  <span>
                    <a onClick={() => this.edit(index,record)}>编辑</a>
                    <span className="ant-divider" />
                    <Link onClick={()=>{window.sessionStorage['details']=JSON.stringify(text)}}  to={{pathname:'/app/deaor',query:{current:this.props.location.query.current,wudi:JSON.stringify(text),ma:'/app/newor'}}}>详情</Link>
                  </span>
              }
            </div>
          )
        }
      }],
		}
	}
  // <span className="ant-divider" />
            // <Link to={{pathname:'/app/newor',query:{state:'编辑','current':this.props.location.current,name:record.name,mobile:record.mobile,address:record.address}}}>编辑</Link>

	onDelete(key,e,_this){
    const data = this.props.orders.table.filter(item => item.key !== key);
  }
  edit(index) {
    const { table } = this.props.orders;

    let _math

    Object.keys(table[index]).forEach((item) => {
      if (table[index][item] && typeof table[index][item].editable !== 'undefined') {
        table[index][item].status = 'save';
        table[index][item].editable = true;
        // this.setState({
        //   _math: table[index][item].value
        // })
      }
    });

    this.props.dispatch({type: 'orders/listEdit',payload: table})

  }
  editDone(index, type,record) {
    let estimated_total;
    const { _math } = this.state
    const { table } = this.props.orders;

    let dataArr;
    let _this = this;
    Object.keys(table[index]).forEach((item) => {
      if (table[index][item] && typeof table[index][item].editable !== 'undefined') {
        table[index][item].editable = false;
        table[index][item].status = type;
      }
    });
    // this.setState({ data },
    Object.keys(table[index]).forEach((item) => {
        if (table[index][item] && typeof table[index][item].editable !== 'undefined') {
          if(type=='save'){
            console.log(table[index])
            table[index][item].value= _math
            table[index][item].status = undefined;
            _this.props.dispatch({type: 'orders/listSave',payload: {table: table , body: {id:  table[index].ID ,estimated_total: _math , aaa:{a:1}} } })
          }else{
            table[index][item].status = undefined
            _this.props.dispatch({type: 'orders/listEdit',payload: table})

          }

        }
      });
    // });
  }
  onA(e){
    this.setState({_math:e.target.value})
  }
  editChange(key, index, value) {
    // this.setState({_math:value})
  }
  renderColumns(data, index, key, text) {
    const { editable, status } = data[index][key];

    if (typeof editable === 'undefined' || editable===false) {
      return text;
    }

    return (<EditableCell
      onA={this.onA.bind(this)}
      editable={editable}
      value={text}
      onHandle={value => this.editChange(key, index, value)}
      state={undefined}
      status={status}
    />);
  }
  handleTableChange(pagination, filters, sorter){
    // console.log(pagination, filters, sorter)
    pagination.tab = '';
    this.props.dispatch({type: 'orders/fetch',payload: pagination})
    this.context.router.push('/app/orders?current=' + this.props.location.query.current + '&page=' + pagination.current)
    // const pager = { ...this.state.pagination };
    // console.log(sorter);
    // console.log(pagination.current)
    // pager.current = pagination.current;
    // this.setState({
    //   pagination: pager,
    // });
    // this.fetch(pagination.current)
    // this.fetch({
    //   results: pagination.pageSize,
    //   page: pagination.current,
    //   sortField: sorter.field,
    //   sortOrder: sorter.order,
    //   ...filters,
    // });
  }
	onSelectChange(selectedRowKeys) {
    // console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  }
  componentWillMount() {
    // this.fetch(1);
    let _current = !this.props.location.query.page && (this.props.orders.list.total/10 > this.props.location.query.page * 1 )
    this.props.dispatch({type: 'orders/fetch',payload:{current: _current  ? this.props.location.query.page : 1, tab: ''}})
    // console.log(_current)

    if (JSON.parse(window.localStorage['setting']).role=='admin') {
      this.state._columns.splice(6,0,{
        title:"介绍人返利",
        dataIndex:'rebate'
      })
    }

  }
  handleTabClick(e) {
    if (e * 1 === 2) {
      this.props.dispatch({ type: 'orders/fetch', payload: { current: 1, tab: '&type=children' } });
    } else {
      this.props.dispatch({ type: 'orders/fetch', payload: { current: 1, tab: '' } });
    }
    this.setState({ tab: e });
  }
  componentWillUnmount() {
    // this.reqwest_server.abort();
  }

  _handleSearch(value) {
    this.setState({ q: value });

    this.props.dispatch({
      type: 'orders/fetch',
      payload: { current: 1, tab: '', q: value },
    });
  }
  exportData() {
    const _this = this;
    _this.props.dispatch({
      type: 'orders/fetch',
      payload: { current: 1, tab: '', q: '', limit: _this.props.orders.pagination.total },
    })
  }
	render() {
		const { selectedRowKeys,data,pagination,loading,dropDown,columns,list,role,tab,_columns } = this.state;
    let _this=this;
    let _table;
    // console.log(this.state.data)
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
      onSelection: this.onSelection,
    };
    const _card = list.map(function(data){
      return <Card  className={`${InStyle.card_list}`} key={data.id}>
        <i >{data.name}</i>
        <i >{data.tel}</i>
        <i >
          <Link to={{pathname:'/app/deaor',query:{wudi:JSON.stringify(data),ma:'/app/newor'}}}>详情</Link>
        </i>
      </Card>
    })
    if(role=='saler_director'||role=='admin'){
      _table=<SalerDirector tab={tab} colu={_columns} onChange={(e,b,c)=>this.handleTableChange(e,b,c)} data={this.props.orders.table} pagination={this.props.orders.pagination} loading={this.props.orders.loading} onTabClick={(e)=>{this.handleTabClick(e)}} columns={columns} />
    }else{
      _table=<Table columns={columns}
        dataSource={this.props.orders.table} onRowClick={this.handleRowClick}
        pagination={this.props.orders.pagination}
        expandedRowRender={record => <div>{record.description}</div>}
        loading={this.props.orders.loading}
        onChange={this.handleTableChange.bind(this)}
      />
    }

    return <Layout style={{ background: '#fff', height: '100%' }}>
        <Content>
          <Row type="flex">
            <Col span={7} xl={{ span: 7 }} xs={7} style={{ padding: '24px 25px 0px' }}>
              <Breadcrumb style={{ fontSize: 14 }}>
                <Breadcrumb.Item>销售订单</Breadcrumb.Item>
              </Breadcrumb>
            </Col>
            <Col xl={{ span: 3, offset: 13 }} lg={{ span: 3, offset: 13 }} md={{ span: 3, offset: 13 }} sm={{ span: 3, offset: 13 }} xs={{ span: 2, offset: 12 }} style={{ lineHeight: '60px', textAlign: 'right' }}>
              <Button>
                <Link
                  to={{
                    pathname: '/app/newor',
                    query: {
                      current: this.props.location.query.current,
                      state: '新建'
                    }
                  }}
                >
                  新建
                </Link>
              </Button>
            </Col>
          </Row>
          <Layout className={`${style.tb_serbor}`}>
          <Row type="flex" className={`${style.tb_ser}`}>
              <Col sm={{ span: 7 }} xs={{ span: 0 }} />
              <Col sm={{ span: 7, offset: 10 }} xs={{ span: 14, offset: 10 }} style={{ textAlign: 'right' }} />
            </Row>
            <Row type="flex" className={`${style.tb_ser}`}>
              <Col sm={{ span: 7 }} xs={{ span: 0 }} >
                <Search placeholder="请输入关键字！" style={{ width: 200 }} onSearch={value => this._handleSearch(value)} />
              </Col>
              <Col sm={{ span: 7, offset: 10 }} xs={{ span: 14, offset: 10 }} style={{ textAlign: 'right' }} >
                <ExcelFile element={<Button onClick={this.exportData.bind(this)} type="primary">导出</Button>}>
                    <ExcelSheet data={this.props.orders.table} name="Employees">
                        <ExcelColumn label="订单号" value="orders"/>
                        <ExcelColumn label="所有者" value="name"/>
                        <ExcelColumn label="面积" value="size"/>
                        <ExcelColumn label="金额(元)" value="estimated_total"/>
                        <ExcelColumn label="日期" value="timer"/>
                    </ExcelSheet>
                </ExcelFile>
              </Col>
            </Row>
            {_table}
          </Layout>
        </Content>
      </Layout>
	}
}

Orders.contextTypes = {
  router: PropTypes.object
};


export default connect(({orders}) => ({orders}))(Orders);
